﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using TestForm.entity;

namespace TestForm
{
    public partial class DbMana : Form
    {
        public static string dbPath = "api.db";
        public DbMana()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 保存交易参数
        /// </summary>
        /// <param name="jybh"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="desc"></param>
        /// <returns></returns>
        private static int insertInterface(string jybh, string input, string output, string desc)
        {
            int count = 0;
            using (SQLiteConnection connection = new SQLiteConnection("Data Source="+dbPath+";Version=3;"))
            {
                connection.Open();
                string insertSql = "INSERT INTO interface_info (infno, input,output,desc) VALUES (@infno, @input,@output, @desc)";
                SQLiteCommand insertCmd = new SQLiteCommand(insertSql, connection);
                insertCmd.Parameters.AddWithValue("@infno", jybh);
                insertCmd.Parameters.AddWithValue("@input", input);
                insertCmd.Parameters.AddWithValue("@output", output);
                insertCmd.Parameters.AddWithValue("@desc", desc);
                count = insertCmd.ExecuteNonQuery();
                connection.Close();
            }
            return count;
        }

        /// <summary>
        /// 删除交易参数
        /// </summary>
        /// <param name="jybh"></param>
        /// <returns></returns>
        private static int deleteInterface(string jybh)
        {
            int count = 0;
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"))
            {
                connection.Open();
                string ideleteSql = "delete  from  interface_info where infno = @infno";
                SQLiteCommand deleteCmd = new SQLiteCommand(ideleteSql, connection);
                deleteCmd.Parameters.AddWithValue("@infno", jybh);
                count = deleteCmd.ExecuteNonQuery();
                connection.Close();
            }
            return count;
        }

        /// <summary>
        ///  更新交易参数
        /// </summary>
        /// <param name="jybh"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="desc"></param>
        /// <returns></returns>
        private static int updateInterface(string jybh,string input,string output,string desc)
        {
            int count = 0;
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"))
            {
                connection.Open();
                string updateSql = "update  interface_info set input = @input,output = @output, desc = @desc where infno = @infno";
                SQLiteCommand updateCmd = new SQLiteCommand(updateSql, connection);
                updateCmd.Parameters.AddWithValue("@infno", jybh);
                updateCmd.Parameters.AddWithValue("@input", input);
                updateCmd.Parameters.AddWithValue("@output", output);
                updateCmd.Parameters.AddWithValue("@desc", desc);
                count = updateCmd.ExecuteNonQuery();
                connection.Close();
            }
            return count;
        }

        /// <summary>
        ///  查询交易参数
        /// </summary>
        /// <param name="jybh"></param>
        /// <returns></returns>
        private static List<InterfaceInfo> selectInterface(string jybh)
        {
            List<InterfaceInfo> item = new List<InterfaceInfo>();
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;"))
            {
                connection.Open();
                string selectSql = "";
                if (jybh == "")
                {
                    selectSql = "select * from interface_info where 1=1 or infno = @infno";
                }
                else
                {
                    selectSql = "select * from interface_info where infno = @infno";
                }
                SQLiteCommand selectCmd = new SQLiteCommand(selectSql, connection);
                selectCmd.Parameters.AddWithValue("@infno", jybh);
                using (SQLiteDataReader reader = selectCmd.ExecuteReader())
                {
                    InterfaceInfo interfaceInfo = null;
                    while (reader.Read())
                    {
                        interfaceInfo = new InterfaceInfo();
                        interfaceInfo.id = reader.GetInt32(0);
                        interfaceInfo.infno = reader.GetInt32(1);
                        interfaceInfo.input = reader.GetString(2);
                        interfaceInfo.output = reader.GetString(3);
                        interfaceInfo.desc = reader.GetString(4);
                        item.Add(interfaceInfo);
                    }
                    connection.Close();
                }
            }
            return item;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = null;
            List<InterfaceInfo> items = selectInterface(textBox1.Text);
            if (items != null && items.Count > 0)
            {
                DataTable dt = TestForm.entity.Extensions.ToDataTable<InterfaceInfo>(items);
                this.dataGridView1.AutoGenerateColumns = false;
                this.dataGridView1.DataSource = dt;
                this.dataGridView1.ClearSelection();
            }
            else
            {
                MessageBox.Show("未查询到数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public static bool IsValidJson(string jsonString)
        {
            try
            {
                JToken.Parse(jsonString);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String jybh = textBox1.Text;
            String input = textBox2.Text;
            String output = textBox3.Text;
            String desc = textBox4.Text;

            if (jybh.Trim() == "" || input.Trim() == "")
            {
                MessageBox.Show("交易编号和交易输入不能为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            bool input_flag = IsValidJson(input);
            if (!input_flag)
            {
                DialogResult result = MessageBox.Show("输入是:"+ input+"\n"+ "确定继续保存此非json字符串？", "确认继续", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {

                }
                else 
                {
                    return;
                }
            }

            bool output_flag = IsValidJson(output);
            if (!output_flag)
            {
                DialogResult result = MessageBox.Show("输出是:" + output + "\n" + "确定继续保存此非json字符串？", "确认继续", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {

                }
                else
                {
                    return;
                }
            }

            List<InterfaceInfo> items = selectInterface(jybh);
            if ((items != null) && (items.Count > 0))
            {
                MessageBox.Show("编号:" + jybh + "数据已存在，请核实。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int count = insertInterface(jybh, input, output, desc);
            if (count > 0)
            {
                MessageBox.Show("保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.textBox1.Text = "";
                this.textBox2.Text = "";
                this.textBox3.Text = "";
                this.textBox4.Text = "";
            }
            else
            {
                MessageBox.Show("保存失败！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                int iii = this.dataGridView1.CurrentRow.Index;
                string infno = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column1"].Value);
                DialogResult result = MessageBox.Show("您确定要删除编号为" + infno + "的记录吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    int count = deleteInterface(infno);
                    if (count > 0)
                    {
                        MessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("删除失败！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择一行！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int iii = this.dataGridView1.CurrentRow.Index;
            string infno = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column1"].Value);
            string input = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column2"].Value);
            string output = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column3"].Value);
            string desc = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column4"].Value);

            this.textBox1.Text = infno;
            this.textBox2.Text = input;
            this.textBox3.Text = output;
            this.textBox4.Text = desc;

            new DbParam(infno).ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                int iii = this.dataGridView1.CurrentRow.Index;
                string infno = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column1"].Value);
                DialogResult result = MessageBox.Show("您确定要修改编号为" + infno + "的记录吗？", "确认修改", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    string input = this.textBox2.Text;
                    string output = this.textBox3.Text;
                    string desc = this.textBox4.Text;

                    if (input == "")
                    {
                        MessageBox.Show("交易输入不能为空！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }


                    bool input_flag = IsValidJson(input);
                    if (!input_flag)
                    {
                        DialogResult result1 = MessageBox.Show("输入是:" + input + "\n" + "确定继续保存此非json字符串？", "确认继续", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result1 == DialogResult.Yes)
                        {

                        }
                        else
                        {
                            return;
                        }
                    }

                    bool output_flag = IsValidJson(output);
                    if (!output_flag)
                    {
                        DialogResult result1 = MessageBox.Show("输出是:" + output + "\n" + "确定继续保存此非json字符串？", "确认继续", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result1 == DialogResult.Yes)
                        {

                        }
                        else
                        {
                            return;
                        }
                    }

                    int count = updateInterface(infno, input, output, desc);

                    if (count > 0)
                    {
                        MessageBox.Show("修改成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("修改失败！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择一行！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int iii = this.dataGridView1.CurrentRow.Index;
            string infno = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column1"].Value);
            string input = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column2"].Value);
            string output = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column3"].Value);
            string desc = Convert.ToString(this.dataGridView1.Rows[iii].Cells["Column4"].Value);

            this.textBox1.Text = infno;
            this.textBox2.Text = input;
            this.textBox3.Text = output;
            this.textBox4.Text = desc;
        }
    }
}
